//
//  ChannerViewController.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/11.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "ChannerViewController.h"
#import "CustomerNetworking.h"
#import "CXChannelCollectionViewCell.h"
#import "ChannerModel.h"
#import <MJRefresh.h>
#import "CXInterActionFirstModel.h"
#import "CXFisrtActionColelctionCell.h"
#import "CXHeaderView.h"
#import "CXChannelInterActionController.h"
#import "CXChannelCollectionResuableView.h"
#import "CXNewChannelCollectionCell.h"
#import "CXDetailFirstViewController.h"
#import "CXSearchModel.h"
#import "CXSearchTableViewCell.h"
#import "FZ_BoFang_Two_ViewController.h"
#import "CXSearchViewController.h"
#import "Reachability.h"

#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
@interface ChannerViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UIScrollView *scrollView;

@property(nonatomic, retain)UICollectionView *collectionView;

@property(nonatomic, retain)UICollectionView *secondCollectionView;

@property(nonatomic, retain)NSMutableArray *firstArray;

@property(nonatomic, retain)NSMutableArray *secondArray;

@property(nonatomic, assign)NSInteger page;

@property(nonatomic, assign)BOOL loading;

@property(nonatomic, retain)UIButton *secondButton;

@property(nonatomic, retain)UIButton *firstButton;

@property(nonatomic, retain)CXHeaderView *headerView;

@property(nonatomic, retain)UISearchBar *searchBar;

@property(nonatomic, retain)UIView *searchBackView;

@property(nonatomic, retain)UITableView *tableView;

@property(nonatomic, retain)NSMutableArray *searchArray;

@property(nonatomic, retain) NSMutableData *asynData;

@property(nonatomic, assign) NSInteger count;

@end

@implementation ChannerViewController

-(void)dealloc{
    [_scrollView release];
    [_collectionView release];
    [_firstArray release];
    [_headerView release];
    [_secondCollectionView release];
    [_searchBackView release];
    [_secondArray release];
    [_secondButton release];
    [_searchBar release];
    [_firstButton release];
    [_searchArray release];
    [_tableView release];
    [_asynData release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    self.searchBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.firstArray = [NSMutableArray array];
    self.secondArray = [NSMutableArray array];
    self.searchArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSearch];
    [self createNavigationTitileButton];
    [self createScrollView];
    
    CXChannelInterActionController *interActionController = [[CXChannelInterActionController alloc] init];
    [self addChildViewController:interActionController];
    interActionController.view.frame = CGRectMake(kWidth, 0, kWidth, kHeight);
    [self.scrollView addSubview:interActionController.view];
    //    [self createSearchBar];
    [self createCollectionView];
    [self createHeaderView];
    [self header];
    [self footer];
    [self loadData];
    
    [self createSearchTableView];
    [self.view insertSubview:self.scrollView aboveSubview:self.tableView];

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(change) userInfo:nil repeats:YES];

}
#pragma mark 定时器监听事件
-(void)change{
    
    self.secondCollectionView.contentOffset = CGPointMake(self.view.frame.size.width * self.count, 0);
    if (self.secondCollectionView.contentOffset.x == self.secondCollectionView.frame.size.width * 3) {
        self.secondCollectionView.contentOffset = CGPointMake(0, 0);
        self.count = 0;
    }
    
    
    self.count++;
    
    
}

-(void)header{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.loading =NO;
        [self loadData:self.page andLoading:NO];
    }];
    [self.collectionView.header beginRefreshing];
}

-(void)footer{
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        self.loading = YES;
        [self loadData:self.page andLoading:YES];
    }];
}
#pragma mark 解析最热数据
-(void)loadData:(NSInteger)page andLoading:(BOOL)loading{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *documentPath = [path stringByAppendingPathComponent:@"CXSave.plist"];
    NSLog(@"%@", documentPath);
    if ([self haveNetWork]) {
    [CustomerNetworking customerWithURL:[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/get?with_sound=0&order=hot&page=%ld", page] andParamer:nil andBlock:^(id response) {
        if (loading == NO) {
            [self.firstArray removeAllObjects];
        }
        
        for (NSDictionary *dic in [[response objectForKey:@"result"] objectForKey:@"data"]) {
            ChannerModel *model = [ChannerModel modelWithDictionary:dic];
            [self.firstArray addObject:model];
        }
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        self.collectionView.header.hidden = YES;
        
        [NSKeyedArchiver archiveRootObject:self.firstArray toFile:documentPath];

    }];
    }
    if ([self haveNetWork] == NO) {
        NSMutableArray *tempAray = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
        self.firstArray = tempAray;
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        [self.collectionView reloadData];
    }

}

- (BOOL)haveNetWork
{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reachability currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"没有网络连接");
            return NO;
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            //            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"号码不可用\n或您的备设不支持拨号功能" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            //            [alertView show];
            return YES;
            break;
        case ReachableViaWiFi:
            // 使用WIFI
            NSLog(@"有网络连接");
            return YES;
        default:
            break;
    }
}

#pragma mark 轮播图
-(void)loadData{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *documentPath = [path stringByAppendingPathComponent:@"CXSaveLoops.plist"];
    if ([self haveNetWork]) {
    [CustomerNetworking customerWithURL:@"http://echosystem.kibey.com/echofamous/tv/tvs" andParamer:nil andBlock:^(id response) {
        for (NSDictionary *dic in [[response objectForKey:@"result"] objectForKey:@"channels"]) {
            CXInterActionFirstModel *model = [CXInterActionFirstModel modelWithDictionary:dic];
            [self.secondArray addObject:model];
        }
        [self.secondCollectionView reloadData];
        
        [NSKeyedArchiver archiveRootObject:self.secondArray toFile:documentPath];

    }];
        
    }
    if ([self haveNetWork] == NO) {
        NSMutableArray *tempAray = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
        self.secondArray = tempAray;
        [self.secondCollectionView reloadData];
    }

    
}
-(void)createHeaderView
{
#pragma mark 创建轮播图
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.secondCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT_PRO(-200), kWidth, HEIGHT_PRO(190)) collectionViewLayout:flowLayout];
    self.secondCollectionView.backgroundColor = [UIColor whiteColor];
    self.secondCollectionView.bounces = NO;
    self.secondCollectionView.pagingEnabled = YES;
    //    [self.secondCollectionView setContentInset:UIEdgeInsetsMake(40, 0, 0, 0)];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.secondCollectionView.delegate = self;
    self.secondCollectionView.dataSource = self;
    //注册cell
    [self.secondCollectionView registerClass:[CXFisrtActionColelctionCell class] forCellWithReuseIdentifier:@"CXFisrtActionColelctionCellID"];
    [self.collectionView addSubview:self.secondCollectionView];
    [_secondCollectionView release];
    [flowLayout release];
    
}
#pragma mark 创建collectionView
-(void)createCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - HEIGHT_PRO(60)) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView setContentInset:UIEdgeInsetsMake(HEIGHT_PRO(200), 0, 0, 0)];
    
    //    [self.collectionView setContentInset:UIEdgeInsetsMake(150, 0, 0, 0)];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //注册cell
    [self.collectionView registerClass:[CXChannelCollectionViewCell class] forCellWithReuseIdentifier:@"CXChannelCollectionViewCellID"];
    [self.scrollView addSubview:self.collectionView];
    [_collectionView release];
    [flowLayout release];
}
#pragma mark 创建scrollView
-(void)createScrollView{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - HEIGHT_PRO(60))];
    self.scrollView.scrollEnabled = NO;
    self.scrollView.delegate = self;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = NO;
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    [self.view addSubview:self.scrollView];
}
#pragma mark 创建左边search小按钮
-(void)createSearch{
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setFrame:CGRectMake(WIDTH_PRO(10), HEIGHT_PRO(10), WIDTH_PRO(25), HEIGHT_PRO(25))];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"iconfont-sousuo"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:searchButton];
}
#pragma mark 创建中间的titleButton
-(void)createNavigationTitileButton{
    
    self.firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.firstButton setFrame:CGRectMake(WIDTH_PRO(140), HEIGHT_PRO(10), WIDTH_PRO(30), HEIGHT_PRO(20))];
    [self.firstButton.titleLabel setFont:[UIFont systemFontOfSize:HEIGHT_PRO(15)]];
    [self.firstButton setTitle:@"最新" forState:UIControlStateNormal];
    [self.firstButton addTarget:self action:@selector(firstButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.firstButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:self.firstButton];
    
    
    self.secondButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.secondButton setFrame:CGRectMake(self.firstButton.frame.size.width + self.firstButton.frame.origin.x + WIDTH_PRO(20), self.firstButton.frame.origin.y, self.firstButton.frame.size.width, self.firstButton.frame.size.height)];
    [self.secondButton.titleLabel setFont:[UIFont systemFontOfSize:HEIGHT_PRO(15)]];
    [self.secondButton setTitle:@"最热" forState:UIControlStateNormal];
    [self.secondButton addTarget:self action:@selector(secondButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.secondButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:self.secondButton];
    
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [playButton setFrame:CGRectMake(self.view.frame.size.width - WIDTH_PRO(40), self.secondButton.frame.origin.y, WIDTH_PRO(20), HEIGHT_PRO(20))];
    [playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yuleguangdieblack.png"] forState:UIControlStateNormal];
    [playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:playButton];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.firstArray.count != 0) {
        if (collectionView == self.collectionView) {
            return self.firstArray.count;
        }
    }
    if (self.secondCollectionView != 0) {
        if (collectionView == self.secondCollectionView) {
            return self.secondArray.count;
        }
    }
    return 0;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.collectionView) {
        CXChannelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXChannelCollectionViewCellID" forIndexPath:indexPath];
        ChannerModel *model = [self.firstArray objectAtIndex:indexPath.row];
        cell.channelModel = model;
        
//        CATransition *anim = [CATransition animation];
//        anim.type = @"cube"; // 动画过渡类型
//        anim.subtype = kCATransitionFromTop; // 动画过渡方向
//        anim.duration = 2; // 动画持续1s
//        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
//        anim.delegate = self;
//        [cell.layer addAnimation:anim forKey:@"key"];
        return cell;
    }
    if (collectionView == self.secondCollectionView) {
        CXFisrtActionColelctionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXFisrtActionColelctionCellID" forIndexPath:indexPath];
        CXInterActionFirstModel *model = [self.secondArray objectAtIndex:indexPath.row];
        
        cell.fisrtModel = model;
//        CATransition *anim = [CATransition animation];
//        anim.type = @"cube"; // 动画过渡类型
//        anim.subtype = kCATransitionFromTop; // 动画过渡方向
//        anim.duration = 2; // 动画持续1s
//        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
//        anim.delegate = self;
//        [cell.layer addAnimation:anim forKey:@"key"];
        return cell;
    }
    
    return nil;
    
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (collectionView == self.secondCollectionView) {
        return 0;
    }
    return HEIGHT_PRO(5);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.secondCollectionView) {
        return  CGSizeMake(kWidth, HEIGHT_PRO(200));
    }
    return CGSizeMake(WIDTH_PRO(184), HEIGHT_PRO(120));
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (collectionView == self.secondCollectionView) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
        
    }
    return UIEdgeInsetsMake(0, 0, HEIGHT_PRO(5), WIDTH_PRO(5));
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchBar resignFirstResponder];
    
    if (collectionView == self.collectionView) {
        CXDetailFirstViewController *detail = [[CXDetailFirstViewController alloc] init];
        ChannerModel *model = [self.firstArray objectAtIndex:indexPath.row];
        detail.channelModel = model;
        detail.bigImage = model.pic;
        detail.detailID = model.ID ;
        detail.name = model.name;
        detail.hidesBottomBarWhenPushed = YES;
        self.navigationController.navigationBar.hidden = YES;
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
    }
    else{
        CXDetailFirstViewController *detail = [[CXDetailFirstViewController alloc] init];
        CXInterActionFirstModel *model = [self.secondArray objectAtIndex:indexPath.row];
        //        detail. = model;
        detail.bigImage = model.pic;
        detail.detailID = model.ID ;
        detail.name = model.name;
        detail.hidesBottomBarWhenPushed = YES;
        self.navigationController.navigationBar.hidden = YES;
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
    }
}
#pragma mark  探索点击事件
-(void)firstButtonAction:(UIButton *)button{
    
    [self.secondButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.firstButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.headerView.hidden = NO;
}

#pragma mark 互动点击事件
-(void)secondButtonAction:(UIButton *)button{
    [self.firstButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.secondButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    self.scrollView.contentOffset = CGPointMake(kWidth, 0);
    self.headerView.hidden = YES;
}
-(void)createSearchBar{
    self.searchBackView = [[UIView alloc] initWithFrame:CGRectMake(0, WIDTH_PRO(-70), kWidth, HEIGHT_PRO(40))];
    self.searchBackView.backgroundColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar addSubview:self.searchBackView];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(WIDTH_PRO(10), 0, self.searchBackView.frame.size.width - WIDTH_PRO(50), HEIGHT_PRO(30))];
    self.searchBar.backgroundColor = [UIColor colorWithRed:0.99 green:0.6 blue:0.69 alpha:1];
    self.searchBar.layer.borderWidth = WIDTH_PRO(0.3);
    self.searchBar.layer.borderColor = [[UIColor grayColor] CGColor];
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.barTintColor = [UIColor whiteColor];
    self.searchBar.tintColor = [UIColor colorWithRed:0.602667 green:0.641333 blue:0.998667 alpha:1];
    self.searchBar.delegate = self;
    self.searchBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self.searchBar becomeFirstResponder];
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    
    self.searchBar.placeholder = @"搜索你要的频道";
    
    [self.searchBackView addSubview:self.searchBar];
    
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(self.searchBackView.frame.size.width - WIDTH_PRO(40), self.searchBar.frame.origin.y, WIDTH_PRO(50), self.searchBar.frame.size.height);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:HEIGHT_PRO(15)];
    [cancelButton setTitleColor:[UIColor colorWithRed:0.43 green:0.84 blue:0.42 alpha:1] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.searchBackView addSubview:cancelButton];
    [_searchBackView release];
    [_searchBar release];
}
#pragma mark 搜索按钮的点击事件
-(void)searchButtonAction:(UIButton *)button{
    [self createSearchBar];
    [self.searchBar becomeFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        self.searchBackView.frame = CGRectMake(0, 0, kWidth, HEIGHT_PRO(40));
    }];
}

#pragma mark 取消按钮的点击事件
-(void)cancelButtonAction:(UIButton *)button{
    [self.searchBar resignFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.searchBackView.frame = CGRectMake(0, HEIGHT_PRO(-70), kWidth, HEIGHT_PRO(40));
    }];
    [self.view insertSubview:self.scrollView aboveSubview:self.tableView];
}


#pragma mark 搜索按钮的代理方法
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchArray removeAllObjects];
    [self.tableView reloadData];
    [self.view insertSubview:self.tableView  aboveSubview:self.scrollView];
    [self searchHeader];
    [self searchFooter];
}

-(void)searchHeader{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.loading =NO;
        [self loadSearchData:self.page andLoading:NO];
    }];
    [self.tableView.header beginRefreshing];

}

-(void)searchFooter{
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        self.loading = YES;
        [self loadSearchData:self.page andLoading:YES];
    }];

}
#pragma mark 以下是有关搜索的代码
-(void)loadSearchData:(NSInteger)page andLoading:(BOOL)loading{
    NSString *utf = [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //http://echosystem.kibey.com/sound/search?keyword=3D&page=1
    NSString *urlString =[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/search?keyword=%@&page=%ld", utf, page];
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [self.asynData appendData:data];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if (loading == NO) {
                        [self.searchArray removeAllObjects];
                    }
                    for (NSDictionary *dic1 in [[dic objectForKey:@"result"] objectForKey:@"data"]) {
                        CXSearchModel *model = [CXSearchModel modelWithDictionary:dic1];
                        [self.searchArray addObject:model];
                    }
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
        self.tableView.header.hidden = YES;
        //
        if (self.searchArray.count == 0 ) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有您要搜索的东西~"  preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            UIAlertAction *defautAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.view insertSubview:self.scrollView aboveSubview:self.tableView];
                [self.searchBar resignFirstResponder];
                [UIView animateWithDuration:0.2 animations:^{
                    self.searchBackView.frame = CGRectMake(0, WIDTH_PRO(-70), kWidth, HEIGHT_PRO(40));
                }];
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:defautAction];
            
            [self presentViewController:alert animated:YES completion:nil];
        }
//判断笑脸
        if (connectionError) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有您要搜索的东西~"  preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            UIAlertAction *defautAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.view insertSubview:self.scrollView aboveSubview:self.tableView];
                [self.searchBar resignFirstResponder];
                [UIView animateWithDuration:0.2 animations:^{
                    self.searchBackView.frame = CGRectMake(0, WIDTH_PRO(-70), kWidth, HEIGHT_PRO(40));
                }];
            }];
            [alert addAction:cancelAction];
            [alert addAction:defautAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];

}
#pragma mark 创建搜索出来得tableView
-(void)createSearchTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    [_tableView release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.searchArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"CXSearchTableViewCellIdentifer";
    CXSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[CXSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    CXSearchModel *model = [self.searchArray objectAtIndex:indexPath.row];
#pragma mark - 关键字高亮
    //设置需要关键字高亮的属性
    NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:model.name];
    //设置范围   如果model.title 和搜索的自相同  则高亮
    NSRange range = [model.name rangeOfString:self.searchBar.text];
    //设置高亮属性
    [mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];

    //设置搜索字体变大
    [mutableString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:33] range:range];
    //将设置的高亮赋给 需要设置的内容
    cell.searchModel = model;
    cell.titleLabel.attributedText = mutableString;
    
    //设置需要关键字高亮的属性
    NSMutableAttributedString *mutableStringInfo = [[NSMutableAttributedString alloc] initWithString:model.info];
    //设置范围   如果model.title 和搜索的自相同  则高亮
    NSRange rangeInfo = [model.info rangeOfString:self.searchBar.text];
    //设置高亮属性
    [mutableStringInfo addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rangeInfo];
    
    //设置搜索字体变大
    [mutableStringInfo addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:rangeInfo];
    //将设置的高亮赋给 需要设置的内容

    cell.infoLabel.attributedText = mutableStringInfo;

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT_PRO(150);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchBar resignFirstResponder];
    CXDetailFirstViewController *detail = [[CXDetailFirstViewController alloc] init];
    detail.navigationController.navigationBarHidden = YES;
    CXSearchModel *model = [self.searchArray objectAtIndex:indexPath.row];
    detail.bigImage = model.pic;
    detail.detailID = model.ID;
    detail.name = model.name;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.searchBar resignFirstResponder];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    [self.searchBar resignFirstResponder];
    if (scrollView == self.tableView) {
        [self.searchBar resignFirstResponder];
    }
}

#pragma mark播放按钮
-(void)playButton:(UIButton *)button{
    FZ_BoFang_Two_ViewController *play = [FZ_BoFang_Two_ViewController sharePlayer];
    play.hidesBottomBarWhenPushed = YES;
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:play animated:YES];
    
    //暂时没释放
//    [play release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated{
    self.searchBar.hidden = YES;
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
